package com.robot.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.robot.common.enums.RobotScanPermissionTypeEnum;
import com.robot.dao.entity.Robot;
import com.robot.dao.feigndto.context.RequestContext;
import com.robot.dao.mapper.RobotMapper;
import com.robot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;


import java.util.ArrayList;
import java.util.List;

@Repository
public class RobotRepository  extends ServiceImpl<RobotMapper, Robot> {
    @Autowired
    private RobotMapper robotMapper;

    @Autowired
    private UserService userService;

    public IPage<RobotRepoEntity> pageQuery( String categoryName, String robotName,Page mpPage) {
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        // 权限控制，能查到：我创建的、管理员创建的、我所在公司创建的。
        RequestContext.UserAccountInfoCtx userAccountInfo= RequestContext.getUserAccountInfo();
        userAccountInfo.getComponyCode();
        List<Long> iDList = userService.getManagerUserIDList();
        iDList.add(userAccountInfo.getUserID());
        queryWrapper.in("user_id", iDList).ne("is_delete", 2);

        if (categoryName!= null) {
            queryWrapper.eq("category_name", categoryName);
        }
        if (robotName!= null &&!robotName.isEmpty()) {
            queryWrapper.like("robot_name", robotName);
        }

        // 执行查询并获取 MyBatis-Plus 的分页结果
        IPage<Robot> mpResult = robotMapper.selectPage(mpPage, queryWrapper);

        Integer totalCount = robotMapper.selectCount(queryWrapper);
        mpResult.setTotal(totalCount);

        IPage<RobotRepoEntity> res = convertIPage(mpResult);

        return res;
    }

    private static IPage<RobotRepoEntity> convertIPage(IPage<Robot> sourcePage) {
        // 创建一个与源页面相同类型的具体实现类的实例作为目标页面
        Page<RobotRepoEntity> targetPage = new Page<>(sourcePage.getCurrent(), sourcePage.getSize());

        // 设置总记录数和总页数到目标页面
        targetPage.setTotal(sourcePage.getTotal());
        targetPage.setPages(sourcePage.getPages());

        // 遍历源页面中的每个Robot对象，进行转换并添加到新的列表中
        List<RobotRepoEntity> targetList = new ArrayList<>();
        for (Robot robot : sourcePage.getRecords()) {
            RobotRepoEntity robotRepository=null;
            try{
                robotRepository = Converter.convert(robot);
            }catch (Exception e){
                System.out.println("RobotRepoEntity robotRepository convert err=");
                e.printStackTrace();
            }

            targetList.add(robotRepository);
        }

        // 将转换后的列表设置到目标页面中
        targetPage.setRecords(targetList);

        return targetPage;
    }

    private static List<RobotRepoEntity> convertPage(List<Robot> sourcePage) {
        List<RobotRepoEntity> targetList = new ArrayList<>();
        // 遍历源列表中的每个Robot对象，通过ObjectConvert进行转换并添加到目标列表
        for (Robot robot : sourcePage) {
            RobotRepoEntity robotRepoEntity = Converter.convert(robot);
            targetList.add(robotRepoEntity);
        }
        return targetList;
    }

    public List<RobotRepoEntity> queryAllRobots(){
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("robot_scan_permission_type", RobotScanPermissionTypeEnum.INDIVIDUAL);
        List<Robot> tempList = robotMapper.selectList(queryWrapper);
        return convertPage(tempList);
    }

    public void updateHeatStar(Long robotId,int heatStar){
        UpdateWrapper<Robot> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", robotId);
        updateWrapper.set("robot_heat_stars",heatStar);
        robotMapper.update(null, updateWrapper);
    }

    public void deleteRobot(Long id){
        UpdateWrapper<Robot> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("is_delete",true);
        robotMapper.update(null,updateWrapper);
    }

    public void updateBasic(RobotRepoEntity robot) {
        UpdateWrapper<Robot> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", robot.getId());

        if (robot.getRobotName()!= null) {
            updateWrapper.set("robot_name", robot.getRobotName());
        }
        if (robot.getRobotUrl()!= null) {
            updateWrapper.set("robot_url", robot.getRobotUrl());
        }
        if (robot.getRobotDescription()!= null) {
            updateWrapper.set("robot_description", robot.getRobotDescription());
        }
        if (robot.getCharacterDesign()!= null) {
            updateWrapper.set("character_design", robot.getCharacterDesign());
        }
        if (robot.getCategoryName()!= null) {
            updateWrapper.set("category_name", robot.getCategoryName());
        }
        if (robot.getIsNeedWebSearching()!= null) {
            updateWrapper.set("is_need_web_searching", robot.getIsNeedWebSearching());
        }
        if (robot.getRobotHeat()!= null) {
            updateWrapper.set("robot_heat", robot.getRobotHeat());
        }
        if (robot.getRobotHeatStars()!= null) {
            updateWrapper.set("robot_heat_stars", robot.getRobotHeatStars());
        }
        if (robot.getViewTimes()!= null) {
            updateWrapper.set("view_times", robot.getViewTimes());
        }
        if (robot.getPrologue()!= null) {
            updateWrapper.set("prologue", robot.getPrologue().convertToJson());
        }
        if (robot.getPrompt_template_info()!= null) {
            updateWrapper.set("prompt_template_info", robot.getPrompt_template_info().convertToJson());
        }
        robotMapper.update(null, updateWrapper);
    }

    public IPage<Robot> queryByUserId(Long userId){
        Page<Robot> page = new Page<>();
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        if (userId!= null) {
            queryWrapper.eq("user_id", userId);
        }
        return robotMapper.selectPage(page, queryWrapper);
    }

    public RobotRepoEntity queryByRobotId(Long robotId){
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", robotId);
        Robot robotDao =robotMapper.selectOne(queryWrapper);
        return Converter.convert(robotDao);
    }

    public List<Robot> queryByCategoryName(String categoryName){
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name", categoryName).ne("is_delete", 2);
        return robotMapper.selectList(queryWrapper);
    }


    public List<Long> queryByCategoryNameLimit(String categoryName, String companyCode){
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id")
                .eq("category_name", categoryName)
                .ne("is_delete", 2)
                .apply("((robot_scan_permission_type = 2 and company_code = {0}) or robot_scan_permission_type = 3)", companyCode)
                .last("limit 2");
        List<Robot> robotList = robotMapper.selectList(queryWrapper);
        List<Long> robotIds = new ArrayList<>();
        for (Robot robot : robotList) {
            robotIds.add(robot.getId());
        }
        return robotIds;
    }

    public Long create(RobotRepoEntity newRobot){
        Robot dao= Converter.convert(newRobot);
        this.save(dao);
        newRobot.setId(dao.getId());
        return dao.getId();
    }

    public List<String> getDistinctCategoryNamesByUserOrCompany(List<Long> userIds, String companyCode) {
        QueryWrapper<Robot> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (companyCode!= null &&!companyCode.isEmpty()) {
            queryWrapper.or().eq("company_code", companyCode);
        }
        queryWrapper.select("distinct(category_name)");
        List<Robot> robotList = robotMapper.selectList(queryWrapper);
        List<String> categoryNames = new ArrayList<>();
        for (Robot robot : robotList) {
            categoryNames.add(robot.getCategoryName());
        }
        return categoryNames;
    }
}
